/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.customer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import src.domain.customer.Cusper;
import src.domain.customer.Customer;
import src.domain.security.Users;
import src.services.CRUEDService;
import src.services.customer.*;
import src.util.Constanta;
import src.util.Messager;
import src.util.Utils;
import src.view.security.LoginBean;

/**
 *
 * @author Yusup Jauhari Shandi <in.visi>
 */

@ManagedBean
@SessionScoped
public class CusperBean  implements java.io.Serializable {
    private List<Cusper> cuspers;

    private List<SelectItem> availableReligion,availableEducation,availableNationality,availableMarstatus,availableSpouserel,
                availableIncomesrc,availableIncomeamt,availableCorebus,availableOccu;
    
    private List<SelectItem> availableProvince,availableDistrict, availableResprovince, availableResdistrict;
    
    private Cusper selectedData, insertedData;
    private boolean editMode=true;
    private CusperModel helper;
    private UploadedFile uploadedFile;
    private static final int BUFFER_SIZE = 6124; 
    private Users user;
    private Cusper filter;
    
    
    public CusperBean() {
        ambilUser();
        this.helper = new CusperModel(); 
        this.cuspers = this.helper.findAll(null);
        this.insertedData = null;
        this.selectedData = null;
        this.filter = new Cusper();
        this.initFilter();
        for (int i=0; i < this.cuspers.size();i++ ){
            CustomerModel x = new CustomerModel();
            this.cuspers.get(i).setCustomer(x.getById(this.cuspers.get(i).getCustomerId()));
        }
    }

    public void initFilter(){
        this.filter.getCustomer().setCustomerName("");
        this.filter.getCustomer().setIdcardNo("");
        this.filter.setMaidenName("");
    }
    
    public Cusper getFilter() {
        return filter;
    }

    public void setFilter(Cusper filter) {
        this.filter = filter;
    }
    
    
    private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.user = logBean.getSelectedUser();
    }
    
    private boolean cekConfig() {
        return (user.getBranch().getBranchId()!=null ? true:false);
    }
    
    private void initForm(){
        ReligionModel religi = new ReligionModel();
        availableReligion = religi.listAll();
        EducationModel edu = new EducationModel();
        availableEducation = edu.listAll();
        NationalityModel nation = new NationalityModel();
        availableNationality = nation.listAll();
        MarstatusModel marit = new MarstatusModel();
        availableMarstatus = marit.listAll();
        SpouserelModel spous = new SpouserelModel();
        availableSpouserel = spous.listAll();
        IncomesrcModel isrc = new IncomesrcModel();
        availableIncomesrc = isrc.listAll();
        IncomeamtModel imt = new IncomeamtModel();
        availableIncomeamt = imt.listAll();
        CorebusModel cr = new CorebusModel();
        availableCorebus = cr.listAll();
        OccuModel oc = new OccuModel();
        availableOccu = oc.listAll();
    }

     public void loadCuspers () {
        Map<String, String> custfilter = new HashMap<>();
      //  savfilter.put("approvalUid", null);
     //   custfilter.put("closeDate", null);
     //   custfilter.put("closedBy", null);
        custfilter.put("order", "customer.cif");
        
                
        this.cuspers = helper.findAll(custfilter);
    }
     
    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
    
    public List<Cusper> getCuspers() {
        return cuspers;
    }
      
    public Cusper getInsertedData() {
        return insertedData;
    }

    public void setInsertedData(Cusper insertedData) {
        this.insertedData = insertedData;
    }

    public Cusper getSelectedData() {        
        return selectedData;
    }

    public void setSelectedData(Cusper selectedData) {
        this.selectedData = selectedData;
    }
    
    public void handleClose(CloseEvent event) {
        this.selectedData = null;
        this.insertedData = null;
        this.editMode = true;      
    }
    
    public void handleCIFChange() {  
        if(insertedData.getCustomer().getCif() !=null && !insertedData.getCustomer().getCif().equals(Constanta.AUTO_NUMBERING)) {
            boolean eksis = new CustomerModel().isCIFExist(insertedData.getCustomer().getCif(), insertedData.getCustomer().getCustomerId());
            if (eksis) {
                Messager.showWarning("cifIsExist");
                insertedData.getCustomer().setCif(Constanta.AUTO_NUMBERING);
            }
        } 
    }  
    
    public void newData() {  
        initForm();
        this.selectedData = null;
        this.editMode = false;
        this.insertedData = new Cusper();
    }
    
    public void openData(){
        initForm();       
        this.editMode = true;
        this.insertedData = Cusper.clone(selectedData);
        handleCountryChange(insertedData.getCustomer().getIdCountryId());
        handleProvinceChange(insertedData.getCustomer().getIdProvinceId());
        handleRescountryChange(insertedData.getCustomer().getResCountryId());
        handleResprovinceChange(insertedData.getCustomer().getResProvinceId());
    }
    
    private void save() {
                
        RequestContext context = RequestContext.getCurrentInstance();
        
        Customer customer = insertedData.getCustomer();
        customer.setLogUpdated(Utils.logActions(user.getUserName(), new java.util.Date()));
        if (!editMode) customer.setLogCreated(Utils.logActions(user.getUserName(), new java.util.Date()));
        
      //  if (uploadedFile!=null){
        //    customer.setSpecimen(uploadedFile.getFileName());
       // }
        customer.setCustomerType(Constanta.CUSTOMER_PERSONAL);
        customer.setCusper(insertedData);
        if (customer.getIdCountryId()==-1) customer.setIdCountryId(null);
        if (customer.getIdProvinceId()==-1) customer.setIdProvinceId(null);
        if (customer.getIdDistrictId()==-1) customer.setIdDistrictId(null);
        if (customer.getRestatusId()==-1) customer.setRestatusId(null);
        
        if (insertedData.getIncomeamtId()==-1) insertedData.setIncomeamtId(null);
        if (insertedData.getIncomesrcId()==-1) insertedData.setIncomesrcId(null);
        if (insertedData.getSpouserelId()==-1) insertedData.setSpouserelId(null);
        if (insertedData.getCorebusId()==-1) insertedData.setCorebusId(null);
        if (insertedData.getEducationId()==-1) insertedData.setEducationId(null);
        
        insertedData.setCustomer(customer);
                       
        boolean success = helper.saveData(customer);
        if (success==true) {
            if (this.editMode==false) this.cuspers.add(insertedData);
            else {
                int i = cuspers.indexOf(selectedData);
                if (i <= cuspers.size()) cuspers.set(i, Cusper.clone(insertedData));
            }
            editMode = true;
            
        } else {
            if (this.editMode==false) {
                insertedData.getCustomer().setCustomerId(null);
                insertedData.setCustomerId(null);
            }
        }
        
        Messager.showSaveUpdateStatus(success);
        context.addCallbackParam("success", success); 
    }
    
    public void delete() {
        RequestContext context = RequestContext.getCurrentInstance();  
        
        Customer customer = selectedData.getCustomer();
        customer.setCusper(selectedData);
        selectedData.setCustomer(customer);
                
        boolean success = helper.deleteData(customer);
        
        if (success) {
            this.cuspers.remove(selectedData);
            this.selectedData = null;
        } 
        
        Messager.showDeleteStatusConstaint(success);  
        context.addCallbackParam("success", success); 
    }
    
    public void trySave() {
        boolean configured = cekConfig();
        if(configured==true) {
            newNumber();
            save();
        } else Messager.showWarning("unconfig");
    }
    
    private void newNumber() {
//        String cif = insertedData.getCustomer().getCif();
//        //Integer branchId = new BranchModel().getBranchPc(src.util.Utils.getClienyIpAddress());
//        if (cif.equals(Constanta.AUTO_NUMBERING)) {
//            cif =  new CRUEDService().getNextTrxNumber(10, user.getBranch().getBranchId(), 0, 1).getTrxNum();
//            insertedData.getCustomer().setCif(cif);
//        }
    }
    
    public void handleCountryChange(Integer country) {  
        if(country !=null ) {
            Map<String, String> filters = new HashMap<>();       
            filters.put("tb.countryId", String.valueOf(country.intValue()));
            ProvinceModel prov = new ProvinceModel();
            this.availableProvince = prov.listAll(filters);  
        } 
    }  
     
     public void handleProvinceChange(Integer province) {  
        if(province !=null ) {
            Map<String, String> filters = new HashMap<>();       
            filters.put("tb.provinceId", String.valueOf(province.intValue()));
            DistrictModel district = new DistrictModel();
            this.availableDistrict = district.listAll(filters);  
        } 
    }  
          
    public void handleRescountryChange(Integer country) {  
        if(country !=null ) {
            Map<String, String> filters = new HashMap<>();       
            filters.put("tb.countryId", String.valueOf(country.intValue()));
            ProvinceModel prov = new ProvinceModel();
            this.availableResprovince = prov.listAll(filters);  
        } 
    }  
     
     public void handleResprovinceChange(Integer province) {  
        if(province !=null ) {
            Map<String, String> filters = new HashMap<>();       
            filters.put("tb.provinceId", String.valueOf(province.intValue()));
            DistrictModel district = new DistrictModel();
            this.availableResdistrict = district.listAll(filters);  
        } 
    }  
     
    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }

    public List<SelectItem> getAvailableCorebus() {
        return availableCorebus;
    }

    public List<SelectItem> getAvailableEducation() {
        return availableEducation;
    }

    public List<SelectItem> getAvailableIncomeamt() {
        return availableIncomeamt;
    }

    public List<SelectItem> getAvailableIncomesrc() {
        return availableIncomesrc;
    }

    public List<SelectItem> getAvailableMarstatus() {
        return availableMarstatus;
    }

    public List<SelectItem> getAvailableNationality() {
        return availableNationality;
    }

    public List<SelectItem> getAvailableOccu() {
        return availableOccu;
    }

    public List<SelectItem> getAvailableReligion() {
        return availableReligion;
    }

    public List<SelectItem> getAvailableSpouserel() {
        return availableSpouserel;
    }

    public List<SelectItem> getAvailableDistrict() {
        return availableDistrict;
    }

    public List<SelectItem> getAvailableProvince() {
        return availableProvince;
    }

    public List<SelectItem> getAvailableResdistrict() {
        return availableResdistrict;
    }

    public List<SelectItem> getAvailableResprovince() {
        return availableResprovince;
    }
 
    public void handleFileUpload(FileUploadEvent event) {
       
    ExternalContext extContext=FacesContext.getCurrentInstance().getExternalContext();
            
    File result = new File(extContext.getRealPath("//upload//personal//" + 
          event.getFile().getFileName()));
    //System.out.println(extContext.getRealPath("//WEB-INF//files//" + 
    //      event.getFile().getFileName()));

    try {
            InputStream inputStream;
            try (FileOutputStream fileOutputStream = new FileOutputStream(result)) {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bulk;
                inputStream = event.getFile().getInputstream();
                while (true) {
                       bulk = inputStream.read(buffer);
                       if (bulk < 0) {
                           break;
                        }
                       fileOutputStream.write(buffer, 0, bulk);
                       fileOutputStream.flush();
                 }
            }
        inputStream.close();
        this.insertedData.getCustomer().setSpecimen(event.getFile().getFileName());
       FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName()
                                                                  + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);

        } catch (IOException e) {

            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, 
                                                 "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
            
     }       
   } 
    
    public String prepareSex(String sex){
        
        if (sex.equals("F"))
            return "Perempuan";
        else
            return  "Laki-Laki";
    }
    
    public void search() {
        Map<String, Object> custfilter = new HashMap<>();
        if ((filter.getCustomer().getCustomerName()!=null)&& !filter.getCustomer().getCustomerName().equals(""))
            custfilter.put("customer.customerName", filter.getCustomer().getCustomerName());
        if ((filter.getBirthDate()!=null)){
            
           
            custfilter.put("birthDate", filter.getBirthDate());
        }
        if ((filter.getCustomer().getIdcardNo()!=null)&& !filter.getCustomer().getIdcardNo().equals(""))
            custfilter.put("customer.idcardNo", filter.getCustomer().getIdcardNo());
        if ((filter.getMaidenName()!=null)&& !filter.getMaidenName().equals(""))
            custfilter.put("maidenName", filter.getMaidenName());
                
        this.cuspers = helper.findAllAdvance(custfilter);
               
        
    }
}
